﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Strom.Server.IO;

/////////////////////////////////
//  Classe de base du serveur  //
/////////////////////////////////

namespace Strom.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Serveur";
            StartUpMessage();
            ServerConsole.WriteLine("\n\n-------------------------------------------------------\n\n", ConsoleColor.Gray);
            Loader.Load();
            ServerConsole.WriteLine("\n\n-------------------------------------------------------\n\n", ConsoleColor.Gray);
            SetConsoleCtrlHandler(HandleConsoleEvents, true);

            while (true)
            {
                Console.Write("<{0}:{1}> ", ServerDatas.IP, ServerDatas.Port);
                Commands.CommandParser.Parse(Commands.CommandParser.GetCommandDatas(Console.ReadLine()));
            }
        }

        #region StartUpMessage

        static void StartUpMessage()
        {
            ServerConsole.WriteLine("Strøm : Moteur de MMORPG 2D", ConsoleColor.DarkCyan);
            Console.WriteLine();
            ServerConsole.WriteLine("Développé par Xynablue et hugoxerox", ConsoleColor.Gray);
        }

        #endregion

        /// <summary>
        /// Si la console se ferme, sauvegarde de toutes les données
        /// </summary>
        /// <param name="ctrlTypes"></param>
        /// <returns></returns>
        static bool HandleConsoleEvents(CtrlTypes ctrlTypes)
        {
            if(ctrlTypes == CtrlTypes.CTRL_CLOSE_EVENT)
            {
                ServerDatas.Server.Database.Save();
                ServerDatas.Server.Stop();
                Core.Config.AutoConfig.SaveConfig("config.xml");
                Environment.Exit(0);
            }
            return true;
        }

        [DllImport("Kernel32")]
        public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
        public delegate bool HandlerRoutine(CtrlTypes CtrlType);

        public enum CtrlTypes
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT,
            CTRL_CLOSE_EVENT,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT
        }
    }
}
